package pers.liyan.shi.springboot.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * springboot-security配置类
 *
 * @author shily
 * @date 2019/3/17 17:32
 */
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //定制请求授权规则
        http.authorizeRequests().antMatchers("/css/**", "/fonts/**", "/js/**", "/", "/checkToken", "/webjars/**").permitAll()
                .antMatchers("/level1/**").hasAnyRole("VIP1", "VIP2", "VIP3", "SVIP")
                .antMatchers("/level2/**").hasAnyRole("VIP2", "VIP3", "SVIP")
                .antMatchers("/level3/**").hasAnyRole("VIP3", "SVIP")
                .antMatchers("/super/**").hasRole("SVIP");

        //开启自动配置的登录功能, 如果没有权限会跳转到登录页面
        /**
         * 1. /login GET请求来到登录页
         * 2. 认证失败会重定向到 /login?error
         * 3. 默认POST的/login请求处理登陆请求
         * 4. 自定义loginPage参数之后, 以POST方式发送的该请求即为登录处理请求, 也可以使用.loginProcessingUrl()方法来指定
         */
        http.formLogin()
                .loginPage("/checkToken")
                .usernameParameter("name")
                .passwordParameter("token");

        /**
         * 1.开启自动配置的注销功能, 访问/logout 并清空session
         * 2.注销成功会返回/login?logout
         * 3.会在响应中增加Set-Cookie: remember-me=; Max-Age=0 来清空rememberme的缓存
         */
        http.logout()
                //注销成功后跳转首页
                .logoutSuccessUrl("/");

        /**
         * 开启记住我功能
         * 登录成功后,在浏览器cookie缓存rememberme信息
         * 以后访问时通过缓存判断
         * 点击注销会删除cookie
         */
        http.rememberMe().rememberMeParameter("remember-me");

    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
                .withUser("xiaozhao").password("123456").roles("VIP1")
                .and()
                .withUser("wuji").password("123456").roles("VIP2")
                .and()
                .withUser("sanfeng").password("123456").roles("VIP3")
                .and()
                .withUser("yangguo").password("123456").roles("VIP3", "SVIP");

    }
}
